package com.cxh.controller.car;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.google.gson.Gson;
import com.cxh.base.BaseController;
import com.cxh.controller.carInterface.CarInterfaceController;
import com.cxh.entity.CarCategory;
import com.cxh.entity.CarDetailBaseInfo;
import com.cxh.entity.CarDetailBody;
import com.cxh.entity.CarDetailChangeSpeedCase;
import com.cxh.entity.CarDetailChassisTurn;
import com.cxh.entity.CarDetailConditionRefrigerator;
import com.cxh.entity.CarDetailControlConfig;
import com.cxh.entity.CarDetailEngine;
import com.cxh.entity.CarDetailGlassMirror;
import com.cxh.entity.CarDetailHighTech;
import com.cxh.entity.CarDetailInConfig;
import com.cxh.entity.CarDetailLightConfig;
import com.cxh.entity.CarDetailMediaConfig;
import com.cxh.entity.CarDetailOutConfig;
import com.cxh.entity.CarDetailSafetyEquipment;
import com.cxh.entity.CarDetailSeatConfig;
import com.cxh.entity.CarDetailWheelBrake;
import com.cxh.entity.CarModel;
import com.cxh.entity.CarModeldataMenu;
import com.cxh.util.CommonUtility;
import com.cxh.util.DateUtility;
import com.cxh.util.json.JSONUtil;

import net.sf.json.JsonConfig;

import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import tk.mybatis.mapper.entity.Example;
import tk.mybatis.mapper.entity.Example.Criteria;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.util.ArrayList;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;


/**
 * 类说明：学生表 
 * @author  ChenXH
 * @date  2018-10-15 14:06:57
 */
@Controller
@RequestMapping(value = "/controller/carModel")
public class CarModelController extends CarInterfaceController {

    /**
     * 方法说明：进入页面
     * @author  ChenXH
     * @date  2018-10-15 14:06:57
     */
    @RequestMapping(value = "/list")
    public ModelAndView list (HttpServletRequest request, HttpServletResponse response){
        ModelAndView model =  new ModelAndView();
        model.setViewName("car/carModel/carModelList");
        return model;
    }

    /**
     * 方法说明：获得表格数据
     * @author  ChenXH
     * @date  2018-10-15 14:06:57
     */
    @RequestMapping(value = "/showList")
    @ResponseBody
    public String showList (HttpServletRequest request, HttpServletResponse response,@RequestParam Map<String, Object> params){
        String json="";
        //获得  页码数
        Integer page=CommonUtility.isEmpty(params.get("page"))?1:Integer.parseInt(params.get("page")+"");
        //获得 每页的行数
        Integer limit=CommonUtility.isEmpty(params.get("limit"))?10:Integer.parseInt(params.get("limit")+"");
        //设置 分页参数
        PageHelper.startPage(page,limit);
        String basePath = request.getScheme()+"://"+request.getServerName()+":"+request.getServerPort()+"/CarManage/";
    	basePath = basePath+"common/img/";
    	params.put("path", basePath);
        //调用 查询方法
        //List<CarModel> carModelList=carModelService.loadPageList(params);
        List<CarModel> carModelList=carModelService.loadPageListPage(params);
        //处理数据
        PageInfo<CarModel> pageInfo=new PageInfo<CarModel>(carModelList);
        try {
            //转换 时间格式/并将数据转换成json字符串
            JsonConfig jsonConfig = JSONUtil.getJsonConfig(DateUtility.DateFormat1);
            json= JSONUtil.toLayUIJSONAll(pageInfo.getTotal(),pageInfo.getList(), jsonConfig);
        }catch (Exception e) {
            e.printStackTrace();
        }
        return json;
    }


    /**
     * 方法说明：进入编辑页面
     * @author  ChenXH
     * @date  2018-10-15 14:06:57
     */
    @RequestMapping(value = "/edit")
    public ModelAndView edit (HttpServletRequest request, HttpServletResponse response){
        //获得要修改数据的Id
        int entityId=CommonUtility.isEmpty(request.getParameter("entityId"))?0:Integer.parseInt(request.getParameter("entityId"));
        ModelAndView model=new ModelAndView();
        //CarModel carModel=new CarModel();
        try {
            //判断是 修改  还是 新增
            if (!CommonUtility.isEmpty(entityId)&&entityId>0) {
                //carModel = carModelService.selectByPrimaryKey(entityId);
                HashMap<String, Object> queryMap = new HashMap<String,Object>();
                queryMap.put("entityid", entityId);
                List<CarModel> loadPageListPage = carModelService.loadPageListPage(queryMap);
                // 进行数据准备
                model.addObject("carModel",loadPageListPage.get(0));
            }
            //查询所有的车系
            List<CarCategory> carCategoryList = carCategoryService.selectAll();
            model.addObject("carCategoryList",carCategoryList);
            //返回视图位置
            model.setViewName("car/carModel/carModelForm");
        } catch (Exception e) {
            e.printStackTrace();
        }
        return model;
    }

    /**
     * 方法说明：保存/修改
     * @author  ChenXH
     * @date  2018-10-15 14:06:57
     */
    @RequestMapping(value = "/save")
    @ResponseBody
    public String save (HttpServletRequest request, HttpServletResponse response,@RequestParam  Map<String,Object> jsonMap,CarModel carModelSave){
        //执行状态（0成功；1失败）
        int flag=0;
        int entityId=CommonUtility.isEmpty(jsonMap.get("entityId"))?0:Integer.parseInt(jsonMap.get("entityId")+"");
        String carcategoryid = jsonMap.get("carcategoryid").toString();
    	String carmodelname = jsonMap.get("carmodelname").toString();
    	String caryear = jsonMap.get("caryear").toString();
    	String carmodelid = jsonMap.get("carmodelid").toString();
    	String otherName = jsonMap.get("otherName").toString();
    	
        //进行 修改
        if(entityId>0){
            CarModel carModel=carModelService.selectByPrimaryKey(entityId);
            if(!CommonUtility.isEmpty(carModel)){
            	//查询是否有重复的数据
        		Example example = new Example(CarModel.class);
        		if(!carmodelid.equals(carModel.getCarmodelid())){
        			Criteria createCriteria = example.createCriteria();
        			createCriteria.andEqualTo("carmodelid",carmodelid);
        			List<CarModel> carModelIdList = carModelService.selectByExample(example);
        			if(carModelIdList.size() != 0 ){
        				return "2";
        			}
        		}
            	//车系类别名称  车型名称  年份是否有重复的
            	if(!carcategoryid.equals(carModelSave.getCarcategoryid()) && !carmodelname.equals(carModelSave.getCarmodelname()) && !caryear.equals(carModelSave.getCaryear())){
            		
            		example.clear();
            		Criteria createCriteria2 = example.createCriteria();
            		createCriteria2.andEqualTo("carcategoryid",carcategoryid);
            		createCriteria2.andEqualTo("carmodelname",carmodelname);
            		createCriteria2.andEqualTo("caryear",caryear);
            		
            		List<CarModel> carModelList = carModelService.selectByExample(example);
            		
            		if(carModelList.size() != 0 ){
            			return "3";
            		}
            	}
            	
            	carModelSave.setId(entityId);
                try {
                    //修改
                	carModelService.updateData(carModelSave,otherName);
                    //carModelService.updateByPrimaryKey(carModelSave);
                    //operationLog(request, "修改用户" + user.getLoginName(), TableConstants.LOG_TYPES_EDIT);
                }catch (Exception e) {
                    flag = 1;
                    e.printStackTrace();
                }
            }else{
                flag=1;
            }
        }else{
            //进行数据添加
            //CarModel carModel=new CarModel();
        	//查询是否有重复的数据
    		Example example = new Example(CarModel.class);
    		Criteria createCriteria = example.createCriteria();
    		createCriteria.andEqualTo("carmodelid",carmodelid);
    		List<CarModel> carModelIdList = carModelService.selectByExample(example);
    		if(carModelIdList.size() != 0 ){
    			return "2";
    		}
            try {
            	//查询是否有重复的数据
        		example.clear();
        		Criteria createCriteria2 = example.createCriteria();
        		createCriteria2.andEqualTo("carcategoryid",carcategoryid);
        		createCriteria2.andEqualTo("carmodelname",carmodelname);
        		createCriteria2.andEqualTo("caryear",caryear);
        		
        		List<CarModel> carModelList = carModelService.selectByExample(example);
        		
        		if(carModelList.size() != 0 ){
        			return "3";
        		}
                //新增
                carModelService.insertData(carModelSave,otherName);
                //operationLog(request, "添加用户" + user.getLoginName(), TableConstants.LOG_TYPES_ADD);
            }catch (Exception e) {
                flag = 1;
                e.printStackTrace();
            }
        }

        return flag+"";
    }

    /**
     * 方法说明：删除
     * @author  ChenXH
     * @date  2018-10-15 14:06:57
     */
    @RequestMapping(value = "/delete")
    @ResponseBody
    public String delete (HttpServletRequest request, HttpServletResponse response){
        int entityId=CommonUtility.isEmpty(request.getParameter("entityId"))?0:Integer.parseInt(request.getParameter("entityId"));
        //执行状态（0成功；1失败）
        int flag = 0;
        if(entityId>0){
            CarModel carModel = carModelService.selectByPrimaryKey(entityId);
            if(!CommonUtility.isEmpty(carModel)){
                //carModel.setIsDel(0);
                try {
                	carModelService.deleteAboutData(carModel);
                    //carModelService.updateByPrimaryKey(carModel);
                    //operationLog(request, "删除用户" + user.getLoginName(), TableConstants.LOG_TYPES_DEL);
                }catch (Exception e) {
                    flag = 1;
                    e.printStackTrace();
                }
            }
        }
        return flag+"";
    }
    
    /**
     * @类功能说明：车型参数的数据维护
     * @作者：Chenxh
     * @创建时间：2018年12月20日下午1:47:09
     */
    @RequestMapping("/dataProject")
    public String dataProject(HttpServletRequest request, HttpServletResponse response,String carmodelid){
    	request.setAttribute("carmodelid", carmodelid);
    	//组装树的数据格式
    	ArrayList<Object> MenuList = new ArrayList<Object>();
    	
    	List<CarModeldataMenu> carModeldataMenuList = carModeldataMenuService.selectAll();
    	for (CarModeldataMenu carModeldataMenu : carModeldataMenuList) {
    		HashMap<String, Object> hashMap = new HashMap<String,Object>();
			
    		hashMap.put("id", carModeldataMenu.getId());
    		hashMap.put("pId", "0");
    		hashMap.put("name", carModeldataMenu.getMenuname());
    		
    		MenuList.add(hashMap);
		}
    	request.setAttribute("carmodelid", carmodelid);
    	Gson gson = new Gson();
    	String json = gson.toJson(MenuList);
    	request.setAttribute("MenuList", json);
    	return "car/carModel/dataProject";
    }

    @RequestMapping("/showIframePage/{carmodelid}/{id}")
    public String showIframePage(@PathVariable String carmodelid,@PathVariable int id,HttpServletRequest request){
    	//根据id查询菜单的url
    	CarModeldataMenu carModeldataMenu = carModeldataMenuService.selectByPrimaryKey(id);
    	request.setAttribute("carmodelid", carmodelid);
    	if(id == 1){
    		//车详情基本信息
    		List<CarDetailBaseInfo> carDetailBaseInfo = getCarDetailBaseInfo(carmodelid);
    		request.setAttribute("carDetailBaseInfo", carDetailBaseInfo.size()==0?new CarDetailBaseInfo():carDetailBaseInfo.get(0));
    	}
    	
		if(id == 2){
			//汽车车身详情
			List<CarDetailBody> carDetailBody = carDetailBody(carmodelid);	
			request.setAttribute("carDetailBody", carDetailBody.size()==0?new CarDetailBody():carDetailBody.get(0));
		}
		
		if(id == 3){
			//汽车发动机详情
			List<CarDetailEngine> carDetailEngine = carDetailEngine(carmodelid);
			request.setAttribute("carDetailEngine", carDetailEngine.size()==0?new CarDetailEngine():carDetailEngine.get(0));
		}
		
		if(id == 4){
			//汽车变速箱详情
			List<CarDetailChangeSpeedCase> carDetailChangeSpeedCase = carDetailChangeSpeedCase(carmodelid);
			request.setAttribute("carDetailChangeSpeedCase", carDetailChangeSpeedCase.size()==0?new CarDetailChangeSpeedCase():carDetailChangeSpeedCase.get(0));
		}
		
		if(id == 5){
			//汽车底盘转向详情
			List<CarDetailChassisTurn> carDetailChassisTurn = carDetailChassisTurn(carmodelid);
			request.setAttribute("carDetailChassisTurn", carDetailChassisTurn.size()==0?new CarDetailChassisTurn():carDetailChassisTurn.get(0));
		}
		
		if(id == 6){
			//汽车车轮制动详情
			List<CarDetailWheelBrake> carDetailWheelBrake = carDetailWheelBrake(carmodelid);
			request.setAttribute("carDetailWheelBrake", carDetailWheelBrake.size()==0?new CarDetailWheelBrake():carDetailWheelBrake.get(0));
		}
		
		if(id == 7){
			//汽车安全装备详情
			List<CarDetailSafetyEquipment> carDetailSafetyEquipment = carDetailSafetyEquipment(carmodelid);
			request.setAttribute("carDetailSafetyEquipment", carDetailSafetyEquipment.size()==0?new CarDetailSafetyEquipment():carDetailSafetyEquipment.get(0));
		}
		
		if(id == 8){
			//汽车安全装备详情
			List<CarDetailControlConfig> carDetailControlConfig = carDetailControlConfig(carmodelid);
			request.setAttribute("carDetailControlConfig", carDetailControlConfig.size()==0?new CarDetailControlConfig():carDetailControlConfig.get(0));
		}
		
		if(id == 9){
			//汽车外部配置详情
			List<CarDetailOutConfig> carDetailOutConfig = carDetailOutConfig(carmodelid);
			request.setAttribute("carDetailOutConfig", carDetailOutConfig.size()==0?new CarDetailOutConfig():carDetailOutConfig.get(0));
		}
		
		if(id == 10){
			//汽车内部配置详情
			List<CarDetailInConfig> carDetailInConfig = carDetailInConfig(carmodelid);
			request.setAttribute("carDetailInConfig", carDetailInConfig.size()==0?new CarDetailInConfig():carDetailInConfig.get(0));
		}
		if(id == 11){
			//汽车坐位配置详情
			List<CarDetailSeatConfig> carDetailSeatConfig = carDetailSeatConfig(carmodelid);
			request.setAttribute("carDetailSeatConfig", carDetailSeatConfig.size()==0?new CarDetailSeatConfig():carDetailSeatConfig.get(0));
		}
		if(id == 12){
			//汽车多媒体配置
			List<CarDetailMediaConfig> carDetailMediaConfig = carDetailMediaConfig(carmodelid);
			request.setAttribute("carDetailMediaConfig", carDetailMediaConfig.size()==0?new CarDetailMediaConfig():carDetailMediaConfig.get(0));
		}
		if(id == 13){
			//汽车灯光配置
			List<CarDetailLightConfig> carDetailLightConfig = carDetailLightConfig(carmodelid);
			request.setAttribute("carDetailLightConfig", carDetailLightConfig.size()==0?new CarDetailLightConfig():carDetailLightConfig.get(0));
		}
		if(id == 14){
			//玻璃后视镜详情
			List<CarDetailGlassMirror> carDetailGlassMirror = carDetailGlassMirror(carmodelid);
			request.setAttribute("carDetailGlassMirror", carDetailGlassMirror.size()==0?new CarDetailGlassMirror():carDetailGlassMirror.get(0));
		}
		if(id == 15){
			//汽车空调冰箱信息
			List<CarDetailConditionRefrigerator> carDetailConditionRefrigerator = carDetailConditionRefrigerator(carmodelid);
			request.setAttribute("carDetailConditionRefrigerator", carDetailConditionRefrigerator.size()==0?new CarDetailConditionRefrigerator():carDetailConditionRefrigerator.get(0));
		}
		if(id == 16){
			//汽车高科技
			List<CarDetailHighTech> carDetailHighTech = carDetailHighTech(carmodelid);
			request.setAttribute("carDetailHighTech", carDetailHighTech.size()==0?new CarDetailHighTech():carDetailHighTech.get(0));
		}
		
    	String menuurl = carModeldataMenu.getMenuurl();
    	return menuurl;
    }
    
}
